package cn.com.inossem.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.netease.nim.uikit.common.util.log.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.inossem.adapter.ApplyHourAdapter;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.config.EventCode;
import cn.com.inossem.http.Api;
import cn.com.inossem.http.NetworkConnectGet;
import cn.com.inossem.http.NetworkConnectPost;
import cn.com.inossem.http.NetworkConnectPut;
import cn.com.inossem.model.EventBean;
import cn.com.inossem.model.HourApplyBean;
import cn.com.inossem.utils.DialogUtil;
import cn.com.inossem.utils.TimeUtil;
import cn.com.inossem.utils.ToastUtil;

/**
 * 提报工时
 */
public class ProjectApplyHourActivity extends RequestActivity {
	private static final int CHOICE_HOUR = 1;
	private static String hourHtml = "总计工时:<font color='#FDB118'><big><big> 0 </big></big></font>小时";
	private static String incomeHtml = "预计收入:<font color='#FDB118'><big><big> 0 </big></big></font>元";
	private boolean isEdit = false;
	private ApplyHourAdapter mAdapter;
	private HourApplyBean hourBean;
	private double realSalary;
	private int orderStatus;
	private String orderId;
	@BindView(R.id.common_title)
	TextView commonTitle;
	@BindView(R.id.common_right_tv)
	TextView commonRightTv;
	@BindView(R.id.project_manHour_total)
	TextView projectManHourTotal;
	@BindView(R.id.project_anticipated_income)
	TextView projectAnticipatedIncome;
	@BindView(R.id.project_apply_expense)
	TextView proAddHour;
	@BindView(R.id.project_apply_manHour)
	TextView proApplyHour;
	@BindView(R.id.pro_title)
	TextView proTitle;
	@BindView(R.id.pro_hour_order)
	TextView proHourOrder;
	@BindView(R.id.pro_hour_wbs)
	TextView proHourWbs;
	@BindView(R.id.pro_hour_approver)
	TextView proHourApprover;
	@BindView(R.id.pro_hour_contract_num)
	TextView proHourContractNum;
	@BindView(R.id.pro_hour_create)
	TextView proHourCreate;
	@BindView(R.id.pro_hour_rv)
	RecyclerView pro_hour_rv;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			try {
				dismissLoadPd();
				switch (msg.what) {
					case 1:
						ToastUtil.show(ProjectApplyHourActivity.this, "提交成功");
						if (orderStatus == 2) {
							EventBus.getDefault().post(new EventBean(EventCode.APPLY_HOUR_SUCC));
						}
						finish();
						break;
					case 2:
						LogUtil.d("123123", (String) msg.obj);
						hourBean = new GsonBuilder().setDateFormat("yyyy.MM.dd").create().fromJson(new JSONObject((String) msg.obj).getString("result"), new TypeToken<HourApplyBean>() {
						}.getType());
						for (HourApplyBean.HourItemBean item : hourBean.items) {
							item.datStr = TimeUtil.getWeek(TimeUtil.getDay(item.dat));
							item.id = "";
						}
						initView();
						break;
					case 3:
						ToastUtil.show(ProjectApplyHourActivity.this, new JSONObject((String) msg.obj).getString("msg"));
						break;
					case 99:
						ToastUtil.show(ProjectApplyHourActivity.this, (String) msg.obj);
						break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	public int getContentViewId() {
		return R.layout.act_project_apply_hour;
	}

	@Override
	public void initAllMembers(Bundle savedInstanceState) {
		super.initAllMembers(savedInstanceState);
		initData();
	}

	private void initData() {
		orderStatus = getIntent().getIntExtra("order_status", -1);
		switch (orderStatus) {
			case -1://申请
				hourBean = new HourApplyBean();
				hourBean.setProjectId(getIntent().getStringExtra("project_id"));
				hourBean.no = getIntent().getStringExtra("hour_id");
				hourBean.approveMail = getIntent().getStringExtra("project_approver");
				hourBean.project.projectName = getIntent().getStringExtra("project_name");
				hourBean.createDate = new Date();
				realSalary = getIntent().getDoubleExtra("hour_realSalary", 0);
				hourBean.projectInfoUser.setAgreementNO(getIntent().getStringExtra("project_contract"));
				hourBean.projectInfoUser.setTimeCode(getIntent().getStringExtra("hour_wbs"));
				hourBean.projectInfoUser.setRealProjectName("");
				initView();
				return;
			case 0://审批中
			case 1://已通过
			case 3://已结算
				findViewById(R.id.project_detail_bottom2).setVisibility(View.GONE);
				break;
			case 2://未通过
				break;
		}
		orderId = getIntent().getStringExtra("order_id");
		if (orderStatus != -1) {
			requestApplyedHour();
		}
	}

	private void initView() {
		commonTitle.setText(getString(R.string.hour_apply_title));
		proAddHour.setText(getString(R.string.pro_add_hour));
		proApplyHour.setText(getString(R.string.expense_apply_submit));
		if (orderStatus == -1 || orderStatus == 2) {
			commonRightTv.setVisibility(View.VISIBLE);
			commonRightTv.setText(getString(R.string.expense_apply_titleR));
		} else if (orderStatus == 0) {
			commonRightTv.setVisibility(View.VISIBLE);
			commonRightTv.setText(getString(R.string.expense_apply_titleR2));
		}
		if (TextUtils.isEmpty(hourBean.projectInfoUser.getRealProjectName())) {
			proTitle.setText(hourBean.project.projectName);
		} else {
			proTitle.setText(hourBean.projectInfoUser.getRealProjectName());
		}
		proHourOrder.setText(getString(R.string.hour_no) + " " + hourBean.no);
		proHourApprover.setText(getString(R.string.project_approver) + " " + hourBean.approveMail);
		proHourCreate.setText(getString(R.string.expense_create) + " " + TimeUtil.getDay(hourBean.createDate));
		findViewById(R.id.common_right_img).setVisibility(View.GONE);
		pro_hour_rv.setLayoutManager(new LinearLayoutManager(this));
		pro_hour_rv.setAdapter(mAdapter = new ApplyHourAdapter(this, this, orderStatus));
		mAdapter.setHourList(hourBean.items);
		proHourWbs.setText(getString(R.string.expense_wbs) + ": " + (null != hourBean.projectInfoUser ? hourBean.projectInfoUser.getTimeCode() : ""));
		proHourContractNum.setText(getString(R.string.hour_agreement_no) + " " + (null != hourBean.projectInfoUser ? hourBean.projectInfoUser.getAgreementNO() : ""));
		notifyHourTotal();
	}

	@OnClick({R.id.common_back, R.id.common_right_tv, R.id.project_apply_expense, R.id.project_apply_manHour})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.common_back:
				finish();
				break;
			case R.id.common_right_tv:
				if (orderStatus == -1 || orderStatus == 2) {
					isEdit = !isEdit;
					commonRightTv.setText(isEdit ? getString(R.string.dialog_cancle) : getString(R.string.expense_apply_titleR));
					proAddHour.setText(isEdit ? getString(R.string.expense_del) : getString(R.string.pro_add_hour));
					proApplyHour.setText(isEdit ? getString(R.string.dialog_cancle) : getString(R.string.expense_apply_submit));
					mAdapter.changeEditStatus(isEdit);
					return;
				}
				showEmailDialog();
				break;
			case R.id.project_apply_expense:
				if (isEdit) {
					//删除工时
					if (hourBean.items.size() < 1) {
						ToastUtil.show(this, getString(R.string.hour_add_null));
					} else {
						for (int i = mAdapter.getItemCount(); i >= 0; i--) {
							if (mAdapter.selArray.get(i)) {
								hourBean.items.remove(i);
							}
						}
						mAdapter.setHourList(hourBean.items);
						notifyHourTotal();
					}
				} else {
					Intent mIntent = new Intent(this, ProjectAddHourActivity.class);
					mIntent.putParcelableArrayListExtra("hour_list", hourBean.items);
					startActivityForResult(mIntent, CHOICE_HOUR);
				}
				break;
			case R.id.project_apply_manHour:
				if (isEdit) {
					onViewClicked(commonRightTv);
				} else {
					if (hourBean.items.size() > 0) {
						requestApplyHour();
					} else {
						ToastUtil.show(this, getString(R.string.hour_add_null));
					}
				}
				break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.item_hour_num:
				DialogUtil.getInstance(this).showDialog(getString(R.string.hour_item_change), (int) v.getTag(), null, DialogUtil.DialogType.NUMBER, 8, new DialogUtil.DialogCallBack() {
					@Override
					public void back(int tag, String content, int which) {
						hourBean.items.get(tag).hours = Integer.parseInt(content);
						mAdapter.changeHourItem(tag, Integer.parseInt(content));
						notifyHourTotal();
					}
				});
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
				case CHOICE_HOUR:
					hourBean.items = data.getParcelableArrayListExtra("choice_hour");
					mAdapter.setHourList(hourBean.items);
					notifyHourTotal();
					break;
			}
		}
	}

	/**
	 * 提交工时
	 */
	private void requestApplyHour() {
		showLoadPd();
		if (orderStatus == -1) {
			new NetworkConnectPost(this, Api.PROJECT_APPLY_HOUR, mHandler, 1, new GsonBuilder().setDateFormat("yyyy.MM.dd").create().toJson(hourBean));
		} else if (orderStatus == 2) {
			new NetworkConnectPut(this, Api.PROJECT_APPLY_HOUR + "/" + hourBean.id, mHandler, 1, new GsonBuilder().setDateFormat("yyyy.MM.dd").create().toJson(hourBean));
		}
	}

	/**
	 * 获取工时
	 */
	private void requestApplyedHour() {
		showLoadPd();
		new NetworkConnectGet(this, Api.PROJECT_APPLYED_HOUR + orderId, mHandler, 2);
	}

	/**
	 * 工时催办邮件
	 */
	private void requestTeEmail() {
		showLoadPd();
		new NetworkConnectGet(this, Api.TE_EMAIL + orderId, mHandler, 3);
	}

	private void notifyHourTotal() {
		if (orderStatus == -1 || orderStatus == 2) {
			hourBean.sumHours = 0;
			hourBean.preIncome = 0;
			if (hourBean.items.size() > 0) {
				for (int i = 0; i < hourBean.items.size(); i++) {
					hourBean.sumHours += hourBean.items.get(i).hours;
				}
				hourBean.preIncome = realSalary / 8 * hourBean.sumHours;
			}
		}
		projectManHourTotal.setText(Html.fromHtml(hourHtml.replace("0", "" + hourBean.sumHours)));
		projectAnticipatedIncome.setText(Html.fromHtml(incomeHtml.replace("0", "" + hourBean.preIncome)));
	}

	private void showEmailDialog() {
		DialogUtil.getInstance(ProjectApplyHourActivity.this).showDialog(getString(R.string.te_email_content), 0, null, DialogUtil.DialogType.PROMPT, 0, new DialogUtil.DialogCallBack() {
			@Override
			public void back(int tag, String content, int which) {
				if (which == -1) {
					requestTeEmail();
				}
			}
		});
	}
}